package qmsz.api.service.impl;

import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import qmsz.api.dao.SMSDAO;
import qmsz.api.dao.SMSTemplateDAO;
import qmsz.api.domain.SMSRecord;
import qmsz.api.domain.SMSTemplate;
import qmsz.api.service.SMSService;
import qmsz.api.service.traits.TWebPost;

@Service
public class SMSServiceImpl implements SMSService, TWebPost {
	
	private static final Logger logger = Logger.getLogger(SMSServiceImpl.class);
	
	private static final Random rng = new Random();
	
	@Value("${qmsz.sms.getSmsBusiness}")
	private String getSmsBusiness;
	
	@Value("${qmsz.sms.appid}")
	private String appid;
	
	@Value("${qmsz.sms.appkey}")
	private String appkey;
	
	@Value("${qmsz.sms.tplcode}")
	private String tplcode;
	
	@Value("#{${qmsz.sms.maxPerDay}}")
	private Integer maxPerDay;
	
	@Value("#{${qmsz.sms.minutesUntilExpire}}")
	private Integer minutesUntilExpire;

	@Autowired
	private SMSTemplateDAO smstplDAO;
	
	@Autowired
	private SMSDAO smsDAO;
	
	@Override
	public int sendSMS(long phone) {
		String phoneStr = String.valueOf(phone);

		if (!checkSMSCount(phoneStr)) { return 4; }
		
		SMSTemplate tpl = querySMSTemplate();
		if (tpl == null) { return 3; }
		
		String smscodeStr = String.valueOf(10000 + rng.nextInt(989999));
		String msg = tpl.getTpl().replaceAll("\\{smscode\\}", smscodeStr);
		
		JSONObject requestBody = new JSONObject();
		requestBody.put("appid", appid);
		requestBody.put("appkey", appkey);
		requestBody.put("content", msg);
		requestBody.put("mobile", phoneStr);
		
		JSONObject responseBody = postURL(requestBody, getSmsBusiness);
		if (responseBody == null) {
			logger.error("SMSServiceImpl: SMS API responsed null");
			return 2;
		} else if (!"200".equals(responseBody.getString("code"))) {
			logger.error("SMSServiceImpl: SMS API responsed fail - " + responseBody);
			return 2;
		}
		
		String task_no = responseBody.getString("task_no");
		SMSRecord smsr = new SMSRecord();
		smsr.setId(task_no);
		smsr.setMobile(phoneStr);
		smsr.setState(1);
		smsr.setVerCode(smscodeStr);
		smsr.setContent(msg);
		
		try {
			return smsDAO.insertSMSRecord(smsr) > 0 ? 0 : 1;
		} catch (Exception e) {
			logger.error("insert error", e);
			return 1;
		}
	}
	
	private boolean checkSMSCount(String phoneStr) {
		boolean flag = false;
		try {
			flag = smsDAO.countSMSRecordToday(phoneStr) < maxPerDay;
		} catch (Exception e) {
			logger.error("query error", e);
			flag = false;
		}
		return flag;
	}
	
	private SMSTemplate querySMSTemplate() {
		SMSTemplate tpl = null;
		try {
			tpl = smstplDAO.findSMSTemplate(tplcode);
		} catch (Exception e) {
			logger.error("query error", e);
			tpl = null;
		}
		return tpl;
	}
	
	@Override
	public boolean checkSMS(long phone, String smscode) {
		boolean flag = false;
		try {
			flag = smsDAO.checkSMSCode(String.valueOf(phone), smscode, minutesUntilExpire) > 0;
		} catch (Exception e) {
			logger.error("query error", e);
			flag = false;
		}
		return flag;
	}
}
